package com.sgb.kjwl.viewmodel.transport;

import android.Manifest;
import android.text.TextUtils;

import androidx.databinding.ObservableField;

import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.CarInfo;
import com.sgb.kjwl.model.entity.ProListEntity;
import com.sgb.kjwl.model.entity.transport.CarTypeAndCarLength;
import com.sgb.kjwl.model.entity.transport.GoodsHallFilterEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.GoodsSourceLocationEntity;
import com.sgb.kjwl.model.entity.transport.MapSourcesEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.repository.TransportRepertory;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.kjwl.view.ui.fragment.transport.MapGoodsFragment;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PermissionUtils;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MapGoodsFramgentModel extends BaseViewModel {

    public String raduis;
    private MapGoodsFragment goodsfragment;
    private TransportRepertory repertory;

    public ObservableField<GoodsHallFilterEntity> filterEntity = new ObservableField<>(new GoodsHallFilterEntity());
    public ObservableField<GoodsSourceLocationEntity> sendLocation = new ObservableField<>(new GoodsSourceLocationEntity());
    public ObservableField<GoodsSourceLocationEntity> purposeLocation = new ObservableField<>(new GoodsSourceLocationEntity());
    public ObservableField<GoodsInfoTypeEntity3> sourceType = new ObservableField<>(new GoodsInfoTypeEntity3());
    Gson gson=new Gson();

    public MapGoodsFramgentModel(MapGoodsFragment fragment, TransportRepertory reper) {
        this.goodsfragment = fragment;
        this.repertory = reper;
    }

    public void getMapList() {
        Map map = new HashMap();
        // map.put("areacode", repertory.getAreaCode());

        if (null != filterEntity.get()) {
            if ((filterEntity.get().getMinWeight() == null)) {
                map.put("minWeight", "");
            } else {
                map.put("minWeight", Double.valueOf(filterEntity.get().getMinWeight()));
            }

            if (filterEntity.get().getMaxWeight() == null) {
                map.put("maxWeight", "");
            } else {
                map.put("maxWeight", Double.valueOf(filterEntity.get().getMaxWeight()));
            }
            if ((filterEntity.get().getMinWeight() == null)) {
                map.put("volume", 0);
            } else {
                map.put("volume", Double.valueOf(filterEntity.get().getVolume()));
            }

            if (filterEntity.get().getMaxWeight() == null) {
                map.put("maxVolume", 0);
            } else {
                map.put("maxVolume", Double.valueOf(filterEntity.get().getMaxVolume()));
            }

            if (TextUtils.isEmpty(filterEntity.get().getShipmentEndTime())) {
                if (TextUtils.isEmpty(filterEntity.get().getShipmentTime())) {
                    map.put("shipmentEndTime", "");
                }
            } else {
                map.put("shipmentEndTime", Long.valueOf(filterEntity.get().getShipmentEndTime()));
            }
            if (!TextUtils.isEmpty(filterEntity.get().getShipmentTime())) {
                map.put("shipmentTime", Long.valueOf(filterEntity.get().getShipmentTime()));
            }else{
                map.put("shipmentTime", "");
            }

            if (null == filterEntity.get().getCarType()) {
                map.put("carTypeNos", "");
            } else {
                List lt = new ArrayList();
                for (GoodsInfoTypeEntity3 entity : filterEntity.get().getCarType()) {
                    lt.add(entity.getNo());
                }
                map.put("carTypeNos", lt);
            }

            if (null == filterEntity.get().getLengthType()) {
                map.put("carLenNos", "");
            } else {
                List lt = new ArrayList();
                for (GoodsInfoTypeEntity3 entity : filterEntity.get().getLengthType()) {
                    lt.add(entity.getNo());
                }
                map.put("carLenNos", lt);
            }
            if (null != sendLocation.get()) {
                if (TextUtils.isEmpty(sendLocation.get().getProvinceNo())) {
                    map.put("provinceNo", "");
                } else {
                    map.put("provinceNo", sendLocation.get().getProvinceNo());
                }
            }

            if (null != sendLocation.get()) {
                if (TextUtils.isEmpty(sendLocation.get().getCityNo())) {
                    map.put("cityNo", "");
                } else {
                    map.put("cityNo", sendLocation.get().getCityNo());
                }
            }
            if (null != sendLocation.get()) {
                if (TextUtils.isEmpty(sendLocation.get().getAreaNo())) {
                    map.put("districtNo", "");
                } else {
                    map.put("districtNo", sendLocation.get().getAreaNo());
                }
            }
            if (null != purposeLocation.get()) {
                if (TextUtils.isEmpty(purposeLocation.get().getProvinceNo())) {
                    map.put("destProvinceNo", "");
                } else {
                    map.put("destProvinceNo", purposeLocation.get().getProvinceNo());
                }
            }

            if (null != purposeLocation.get()) {
                if (TextUtils.isEmpty(purposeLocation.get().getCityNo())) {

                    map.put("destCityNo", "");
                } else {
                    map.put("destCityNo", purposeLocation.get().getCityNo());
                }
            }
            if (null != purposeLocation.get()) {
                if (TextUtils.isEmpty(purposeLocation.get().getAreaNo())) {
                    map.put("destDistrictNo", "");
                } else {
                    map.put("destDistrictNo", purposeLocation.get().getAreaNo());
                }
            }

          /*  if (filterEntity.get().getPattern() == -1) {
                map.put("pattern", "");
            } else {
                map.put("pattern", filterEntity.get().getPattern());
            }*/
            if (null != sourceType) {
                if (TextUtils.isEmpty(sourceType.get().getNo())) {
                    map.put("goodsModeNo", "");
                } else {
                    map.put("goodsModeNo", sourceType.get().getNo());
                }
            }

           if(goodsfragment.currentLatLng!=null) {
               map.put("searchLongitude", goodsfragment.currentLatLng.longitude);
               map.put("searchLatitude", goodsfragment.currentLatLng.latitude);
           }

        }
        if(goodsfragment.getActivity()==null){
            return;
        }
        if (PermissionUtils.checkPermissionsGroup(goodsfragment.getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION})) {
            map.put("ipLongitude", SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, ""));
            map.put("ipLatitude", SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, ""));
        }
        map.put("radius", raduis);
        DialogHelper.showProgressDialog(goodsfragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        APIManager.getInstance().getDriverAPI().getNewMapGoodsSourcesList(map).enqueue(new Callback<BaseEntity<List<MapSourcesEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<MapSourcesEntity>>> call, Response<BaseEntity<List<MapSourcesEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;

                if (response.body().getState().equals("ok")) {
//                    Log.v("responsBody===",new Gson().toJson(response.body().getData()));
                    goodsfragment.showMapList(response.body().getData());
                } else {
//                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<MapSourcesEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getBussMapList() {
        Map map = new HashMap();
        map.put("areacode", repertory.getAreaCode());
        map.put("limit", "20");
        map.put("page", "1");
        List lt = new ArrayList();
        map.put("carTypeNos", lt);

        List lts = new ArrayList();
        map.put("carLenNos", lts);
        map.put("goodsModeNo", "");
        map.put("destDistrictNo", "");
        map.put("destCityNo", "");
        map.put("destProvinceNo", "");
        map.put("districtNo", "");
        map.put("cityNo", "");
        map.put("provinceNo", "");


        DialogHelper.showProgressDialog(goodsfragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        APIManager.getInstance().getDriverAPI().getNewMapGoodsBusList(map).enqueue(new Callback<BaseEntity<ProListEntity<List<MapSourcesEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ProListEntity<List<MapSourcesEntity>>>> call, Response<BaseEntity<ProListEntity<List<MapSourcesEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;

                if (response.body().getState().equals("ok")) {
//                    Log.v("responsBody===",new Gson().toJson(response.body().getData()));
                    goodsfragment.showBusMapList(response.body().getData().getList());
                } else {
//                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ProListEntity<List<MapSourcesEntity>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getAddressModel() {
        DialogHelper.showProgressDialog(goodsfragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        AddressHelper.getInstance().getAllArea(new AddressHelper.CallBack() {
            @Override
            public void initialData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {

                if (data != null && data.size() > 0) {
                    goodsfragment.initAddressData(data);
                }
            }

            @Override
            public void threeData(List<AddressEntity> provinceList, List<List<AddressEntity>> cityList, List<List<List<AddressEntity>>> districtList) {

            }
        });
    }

    public void getGoodsType() {
        String json = MkvUtils.get().getString(MkvUtils.CacheModular, CacheMarker.LogisticsGoodsType, "");
        if (!TextUtils.isEmpty(json)) {
            List<GoodsInfoTypeEntity3> data = new Gson().fromJson(json, new TypeToken<List<GoodsInfoTypeEntity3>>() {
            }.getType());
            goodsfragment.getGoodsTypeData(data);
        }
        DialogHelper.showProgressDialog(goodsfragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        NewAPIManager.getInstance().getLogisticsAPI().getAllGoodsType().enqueue(new Callback<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Response<BaseEntity<List<GoodsInfoTypeEntity3>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;

                if (response.body().getState().equals("ok")) {
                    //获取从网络请求下来的数据的哈希值
                    String dataJson = DatalUtils.getInstance().getJsonString(response.body().getData());
                    String mHashNet = DatalUtils.strToHashKey(dataJson);
                    String hashData = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.LogisticsGoodsType);
                    if (!mHashNet.equals(hashData)) {
                        goodsfragment.getGoodsTypeData(response.body().getData());
                        MkvUtils.get().putString(MkvUtils.CacheModular, CacheMarker.LogisticsGoodsType, dataJson);
                    }
                } else {
//                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //货车类型
    public void getCarsType() {
        APIManager.getInstance().getDriverAPI().getCarType("1").enqueue(new Callback<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Response<BaseEntity<List<GoodsInfoTypeEntity3>>> response) {
                if (response.body() == null) return;

                if (response.body().getState().equals("ok")) {
                    goodsfragment.getCarsTypeData(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Throwable t) {
            }
        });
    }

    //货车长度
    public void getCarsLength() {
        APIManager.getInstance().getDriverAPI().getCarLenType("1").enqueue(new Callback<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Response<BaseEntity<List<GoodsInfoTypeEntity3>>> response) {
                if (response.body() == null) return;

                if (response.body().getState().equals("ok")) {
                    goodsfragment.getCarsLengthData(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Throwable t) {
            }
        });
    }

    public void getCarInfo() {
        DialogHelper.showProgressDialog(goodsfragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getDriverAPI().getCarInfo().enqueue(new Callback<BaseEntity<List<CarInfo>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<CarInfo>>> call, Response<BaseEntity<List<CarInfo>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    goodsfragment.showCarInfo(response.body().getData());
                } else {
                    MToast.showToast(goodsfragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<CarInfo>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getLocationModel() {

        String areaName = sendLocation.get().getAreaName();
        String provinceName = sendLocation.get().getProvinceName();
        String cityName = sendLocation.get().getCityName();
        if(TextUtils.isEmpty(cityName)){
            cityName=provinceName;
        }
        if(cityName.equals("不限")){
            cityName=provinceName;
        }
        if(TextUtils.isEmpty(areaName)){
            areaName="";
        }
        GeocodeSearch geocodeSearch = new GeocodeSearch(goodsfragment.getActivity());
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

                if (i == 1000) {
                    if (geocodeResult != null && geocodeResult.getGeocodeAddressList() != null &&
                            geocodeResult.getGeocodeAddressList().size() > 0) {

                        GeocodeAddress geocodeAddress = geocodeResult.getGeocodeAddressList().get(0);
                        double latitude = geocodeAddress.getLatLonPoint().getLatitude();//纬度
                        double longititude = geocodeAddress.getLatLonPoint().getLongitude();//经度
                        String adcode = geocodeAddress.getAdcode();//区域编码
                        MLog.d("地理编码", geocodeAddress.getAdcode() + "");
                        MLog.d("纬度latitude", latitude + "");
                        MLog.d("经度longititude", longititude + "");
                        goodsfragment.showLocation(geocodeAddress.getLatLonPoint());

                    } else {
                        MToast.showToast(goodsfragment.getActivity(), "地址名出错");
                    }
                }
            }
        });

        GeocodeQuery geocodeQuery = new GeocodeQuery(cityName + areaName, cityName);
        geocodeSearch.getFromLocationNameAsyn(geocodeQuery);
    }

    public void getCarTypeAndCarLengthList(String goodsTypeNo) {
        if (TextUtils.isEmpty(goodsTypeNo)) {
            goodsTypeNo = "";
        }
        DialogHelper.showProgressDialog(goodsfragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        String finalGoodsTypeNo = goodsTypeNo;
        NewAPIManager.getInstance().getLogisticsAPI().getCarTypeAndLengthList(goodsTypeNo).enqueue(new Callback<BaseEntity<List<CarTypeAndCarLength>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<CarTypeAndCarLength>>> call, Response<BaseEntity<List<CarTypeAndCarLength>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null)
                    return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    goodsfragment.setCarTypeAndCarLength(finalGoodsTypeNo, response.body().getData());
                }else {
                    MToast.showToast(goodsfragment.getActivity(), response.body().getState());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<CarTypeAndCarLength>>> call, Throwable t) {

            }
        });
    }
}
